<?php

// +----------------------------------------------------------------------
// | 分销管家
// +----------------------------------------------------------------------
// | Copyright (c) 2015 http://www.kmeen.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xzake <http://www.kmeen.com>
// +----------------------------------------------------------------------

namespace Common\Model;

use Think\Model;
use Think\Log;

/**
 * 分类模型
 * @author xzake
 */
class MemberModel extends Model {

    /**
     * 自动验证规则
     * @author xzake
     */
    protected $_validate = array(
        array('name', 'require', '真实姓名不能为空', self::MUST_VALIDATE, 'regex', self::MODEL_UPDATE),
        array('nickname', '1,30', '真实姓名长度为1-30个字符', self::EXISTS_VALIDATE, 'length', self::MODEL_UPDATE),
        //验证邮箱
        array('email', 'email', '邮箱格式不正确', self::EXISTS_VALIDATE, 'regex', self::MODEL_UPDATE),
        array('email', '1,32', '邮箱长度为1-32个字符', self::EXISTS_VALIDATE, 'length', self::MODEL_UPDATE),
        array('email', '', '邮箱被占用', self::EXISTS_VALIDATE, 'unique', self::MODEL_UPDATE),
        //验证手机号码
        array('phone', '/^1\d{10}$/', '手机号码格式不正确', self::EXISTS_VALIDATE, 'regex', self::MODEL_UPDATE),
        array('phone', '', '手机号被占用', self::EXISTS_VALIDATE, 'unique', self::MODEL_UPDATE),
    );

    /**
     * 自动完成规则
     * @author xzake
     */
    protected $_auto = array(
        array('create_time', NOW_TIME, self::MODEL_INSERT),
        array('update_time', NOW_TIME, self::MODEL_BOTH),
        array('status', '1', self::MODEL_INSERT),
    );

    public function saveUsers($fromusername, $ticket = FALSE, $idenify = "ticket") {

        $data = array();
        $map = array();
        if (is_array($fromusername)) {
            $data = $fromusername;
            if (!isset($data["openid"])) {
                return false;
            }
            $map["openid"] = array("eq", $data["openid"]);
        } else {
            $idenify = "ticket";
            $map["openid"] = array("eq", $fromusername);
            $data['openid'] = $fromusername;
        }

        $temp = $this->where($map)->find();

        if (empty($temp)) {
            // $data['ticket'] = $fromusername;
            if ($ticket) {

                $map = array();
                $map[$idenify] = array("eq", $ticket);
                $parent = $this->where($map)->find();
                if (empty($parent)) {
                    return $this->saveNormalUser($data);
                } else {
                    return $this->saveTicketUser($data, $parent);
                }
            } else {
                return $this->saveNormalUser($data);
            }
        }
    }

    private function saveNormalUser($data) {
        Log::write("用户普通关注");

        $data['pid'] = 0;
        $data['lft'] = 1;
        $data['rgt'] = 2;
        $data['lvl'] = 0;
        $data['flag'] = 0;
        $time = time();
        $data['create_time'] = $time;
        $data['update_time'] = $time;
        $data['status'] = 1;
        Log::write("准备写入用户信息:" . json_encode($data));
        $id = $this->add($data);
        if (id) {
            Log::write("写入用户信息成功:$id");
            $td["id"] = $id;
            $td["flag"] = $id;
            $this->save($td);
            return $id;
        } else {
            Log::write("写入用户信息失败");
        }
        return false;
    }

    private function saveTicketUser($data, $parent) {
        $pkey = $parent['rgt'];
        $data['pid'] = $parent['id'];
        $data['lft'] = $pkey;
        $data['rgt'] = $pkey + 1;
        $data['lvl'] = $parent['lvl'] + 1;
        $data['flag'] = $parent['flag'];
        $time = time();
        $data['create_time'] = $time;
        $data['update_time'] = $time;
        $data['status'] = 1;
        Log::write("准备写入用户信息:" . json_encode($data));

        $id = $this->add($data);
        if ($id) {
            Log::write("写入用户信息成功:$id");
            $rmap = array();
            $rmap["flag"] = array("eq", $parent['flag']);
            $rmap["rgt"] = array("egt", $pkey);
            $rmap["id"] = array("neq", $id);

            $this->where($rmap)->setInc('rgt', 2);
            Log::write("更新用户关系rgt" . M()->getLastSql());
            $lmap = array();
            $lmap["flag"] = array("eq", $parent['flag']);
            $lmap["lft"] = array("gt", $pkey);
            $lmap["id"] = array("neq", $id);

            $this->where($lmap)->setInc('lft', 2);
            Log::write("更新用户关系lft" . M()->getLastSql());
            return $id;
        } else {
            Log::write("写入用户信息失败");
        }
        return false;
    }

    /**
     * 用户登录
     * @author xzake
     */
    public function login($data) {

        $map['openid'] = array('eq', $data['openid']);
        $user = $this->where($map)->find(); //查找用户
        $id = 0;
        if (!$user) {
            if (isset($data["id"])) {
                $id = $data["id"];
                unset($data["id"]);
                $id = $this->saveUsers($data, $id, "id");
            } elseif (isset($data["ticket"])) {
                $ticket = $data["ticket"];
                unset($data["ticket"]);
                $id = $this->saveUsers($data, $ticket, "ticket");
            } else {
                $id = $this->saveUsers($data);
            }
        }
        //更新登录信息
        $sdata = array(
            'id' => empty($user) ? $id : $user['id'],
            'nickname' => $data['nickname'],
            'info' => $data['info'],
            'login_count' => array('exp', '`login_count`+1'),
            'login_time' => NOW_TIME,
            'login_ip' => get_client_ip(1),
        );
        $this->save($sdata);
        $this->autoLogin($user);
        return empty($user) ? $id : $user['id'];
    }

    /**
     * 设置登录状态
     * @author xzake
     */
    public function autoLogin($user) {
        //记录登录SESSION和COOKIES
        $auth = array(
            'uid' => $user['id'],
            'login_time' => $user['login_time'],
            'login_ip' => get_client_ip(1),
        );
        session('member_auth', $auth);
        session('member_auth_sign', $this->dataAuthSign($auth));
    }

    /**
     * 数据签名认证
     * @param  array  $data 被认证的数据
     * @return string       签名
     * @author xzake
     */
    public function dataAuthSign($data) {
        //数据类型检测
        if (!is_array($data)) {
            $data = (array) $data;
        }
        ksort($data); //排序
        $code = http_build_query($data); //url编码并生成query字符串
        $sign = sha1($code); //生成签名
        return $sign;
    }

    /**
     * 检测用户是否登录
     * @return integer 0-未登录，大于0-当前登录用户ID
     * @author xzake
     */
    public function isLogin() {
        $user = session('member_auth');
        if (empty($user)) {
            return 0;
        } else {
            return session('member_auth_sign') == $this->dataAuthSign($user) ? $user['uid'] : 0;
        }
    }
    
  
    
}
